import { StyleSheet, Text, View, Image, TouchableWithoutFeedback } from 'react-native'
import React, { useState, useCallback, useRef } from 'react'
import axios from '../../axios'
import { getDomain } from '../../utils/tools'
import Dialog from '../../components/Dialog'
import AlbumList from '../../components/Album/AlbumList'
import { useFocusEffect } from '@react-navigation/native'

const Market = ({ user }) => {
  const [list, setList] = useState([])
  const [myList, setMyList] = useState([])
  const [status, setStatus] = useState('loading')
  const [query, setQuery] = useState({
    index: 1,
    size: 6
  })
  
  const dialogRef = useRef(null)
  const [editId, setEditId] = useState('')
  
  useFocusEffect(
    useCallback(() => {
      axios.get('/fan/news', query).then(res => {
        setList([...list, ...res.data.records])
        setMyList(res.myList)
        console.log(res.data.records.length)
        console.log('list', list.length)
        console.log('myList', myList.length)

        if (res.data.records.length < query.size) setStatus('noMore')
        else setStatus('more')
      }).catch(err => { })
    }, [query])
  )

  const onEndReached = () => {
    if (status === 'noMore') return
    setStatus('loading')
    setQuery({
      ...query,
      index: query.index + 1
    })
  }
  const open = (id) => {
    console.log(id)
    setEditId(id)
    dialogRef.current.open()
  }
  const del = () => {
    axios.delete('/news', {
      id: editId
    }).then(() => {
      if(myList.some(item => item._id === editId)) {
        setMyList(myList.filter(item => item._id !== editId))
      } else {
        setList(list.filter(item => item._id !== editId))
      }
      dialogRef.current.close()
    }).catch(err => { })
  }
  return (
    <>
      <Dialog ref={dialogRef} confirm={del}></Dialog>
      <AlbumList data={[...myList, ...list]} status={status} onEndReached={onEndReached} del={open}></AlbumList>
    </>
  )
}

export default Market

const styles = StyleSheet.create({})